﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Engine.Physics
{
    public class PhysicsManager : Manager
    {
        private List<IPhysicEntity> activeObjects;
        private List<IForce> forcesList;

        public Vector3 Gravity { get; set; }

        private static PhysicsManager _instance;
        public static PhysicsManager Instance { get { return _instance; } }

        public PhysicsManager()
        {
            if (_instance != null)
                throw new Exception("Only one instance can be created");
            _instance = this;
            activeObjects = new List<IPhysicEntity>(16);
            forcesList = new List<IForce>(4);
        }

        public void Add(IPhysicEntity physicsObject)
        {
            activeObjects.Add(physicsObject);
        }

        public void Remove(IPhysicEntity physicsObject)
        {
            activeObjects.Remove(physicsObject);
        }

        public override void Update(GameTime gameTime)
        {
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            foreach (var o in activeObjects)
            {
                foreach (var force in forcesList)
                {
                    o.Acceleration += force.Direction / o.Mass; 
                }

                o.Acceleration += Gravity;
                o.Velocity += o.Acceleration * dt;
                o.Velocity *= o.Drag;
                o.Position += o.Velocity * dt;
            }
            base.Update(gameTime);
        }

    }
}
